import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:math';
import 'package:animated_flip_counter/animated_flip_counter.dart';

class WebViewPage extends StatefulWidget {
  const WebViewPage({super.key, required this.title});
  final String title;
  @override
  State<StatefulWidget> createState() => _WebViewPageState();
}

class _WebViewPageState extends State<WebViewPage> {
  String title = "";
  @override
  void initState() {
    title = widget.title;
    super.initState();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    final routeArgs = ModalRoute.of(context)?.settings.arguments;
    if (routeArgs is Map<String, dynamic>) {
      setState(() {
        title = routeArgs['title'] ?? widget.title;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 原来的随机数字动画器
            Padding(
              padding: const EdgeInsets.all(20.0),
              child: Card(
                elevation: 5,
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Column(
                    children: [
                      Text(
                        '自定义动画效果',
                        style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                      ),
                      const SizedBox(height: 10),
                      RandomNumberAnimator(
                        style: TextStyle(fontSize: 36, fontWeight: FontWeight.bold),
                      ),
                    ],
                  ),
                ),
              ),
            ),
            
            // 使用animated_flip_counter库的动画效果
            Padding(
              padding: const EdgeInsets.all(20.0),
              child: Card(
                elevation: 5,
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Column(
                    children: [
                      Text(
                        'AnimatedFlipCounter效果',
                        style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
                      ),
                      const SizedBox(height: 10),
                      FlipCounterExample(),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      )
    );
  }
}

class RandomNumberAnimator extends StatefulWidget {
  final TextStyle? style;
  
  const RandomNumberAnimator({
    Key? key,
    this.style,
  }) : super(key: key);

  @override
  State<RandomNumberAnimator> createState() => _RandomNumberAnimatorState();
}

class _RandomNumberAnimatorState extends State<RandomNumberAnimator> with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Timer _timer;
  int _currentValue = 0;
  final Random _random = Random();
  
  // 模拟真实数据
  final List<int> _realData = [1234, 5678, 9012, 3456, 7890, 2345, 6789, 1357, 2468, 8642];
  int _dataIndex = 0;
  
  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 500),
    );
    
    // 每隔2秒更新一次数字
    _timer = Timer.periodic(const Duration(seconds: 2), (timer) {
      setState(() {
        // 随机选择是显示随机数还是真实数据
        if (_random.nextBool()) {
          _currentValue = _random.nextInt(10000); // 生成随机数
        } else {
          _currentValue = _realData[_dataIndex]; // 使用真实数据
          _dataIndex = (_dataIndex + 1) % _realData.length; // 循环使用真实数据
        }
      });
      
      // 重置并启动动画
      _controller.reset();
      _controller.forward();
    });
    
    // 初始值
    _currentValue = _realData[0];
    _controller.forward();
  }
  
  @override
  void dispose() {
    _controller.dispose();
    _timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _controller,
      builder: (context, child) {
        return Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              '数据统计',
              style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
            ),
            const SizedBox(height: 20),
            Text(
              _currentValue.toString(),
              style: widget.style,
            ),
            const SizedBox(height: 20),
            Text(
              '(每2秒更新一次)',
              style: TextStyle(fontSize: 16, color: Colors.grey),
            ),
          ],
        );
      },
    );
  }
}

class AnimatedCounter extends ImplicitlyAnimatedWidget {
  final int value;
  final TextStyle? style;

  AnimatedCounter({
    Key? key,
    required this.value,
    this.style,
    Curve curve = Curves.easeInOut,
    required Duration duration,
  }) : super(key: key, curve: curve, duration: duration);

  @override
  ImplicitlyAnimatedWidgetState<ImplicitlyAnimatedWidget> createState() => _AnimatedCounterState();
}

class _AnimatedCounterState extends AnimatedWidgetBaseState<AnimatedCounter> {
  IntTween? _value;

  @override
  void forEachTween(TweenVisitor<dynamic> visitor) {
    _value = visitor(
      _value,
      widget.value,
      (dynamic value) => IntTween(begin: value as int),
    ) as IntTween?;
  }

  @override
  Widget build(BuildContext context) {
    return Text(
      '${_value!.evaluate(animation)}',
      style: widget.style,
    );
  }
}

// 使用animated_flip_counter库的示例组件
class FlipCounterExample extends StatefulWidget {
  const FlipCounterExample({Key? key}) : super(key: key);

  @override
  State<FlipCounterExample> createState() => _FlipCounterExampleState();
}

class _FlipCounterExampleState extends State<FlipCounterExample> {
  double _value = 0;
  final Random _random = Random();
  late Timer _timer;
  
  // 模拟真实数据
  final List<double> _realData = [1234.56, 5678.90, 9012.34, 3456.78, 7890.12, 2345.67];
  int _dataIndex = 0;

  @override
  void initState() {
    super.initState();
    
    // 每隔3秒更新一次数字
    _timer = Timer.periodic(const Duration(seconds: 3), (timer) {
      setState(() {
        // 随机选择是显示随机数还是真实数据
        if (_random.nextBool()) {
          _value = _random.nextDouble() * 10000; // 生成随机数
        } else {
          _value = _realData[_dataIndex]; // 使用真实数据
          _dataIndex = (_dataIndex + 1) % _realData.length; // 循环使用真实数据
        }
      });
    });
    
    // 初始值
    _value = _realData[0];
  }
  
  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        // 基本数字翻转效果
        AnimatedFlipCounter(
          value: _value,
          duration: const Duration(milliseconds: 500),
          curve: Curves.elasticOut,
          textStyle: TextStyle(fontSize: 40, fontWeight: FontWeight.bold, color: Colors.blue),
          fractionDigits: 2, // 显示2位小数
          prefix: "¥", // 前缀
        ),
        
        const SizedBox(height: 20),
        
        // 带有更多自定义的数字翻转效果
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            AnimatedFlipCounter(
              value: _value.toInt(),
              duration: const Duration(milliseconds: 500),
              textStyle: TextStyle(
                fontSize: 30,
                fontWeight: FontWeight.bold,
                color: Colors.green,
                letterSpacing: 2.0,
              ),
              prefix: "数量: ",
            ),
            const SizedBox(width: 20),
            AnimatedFlipCounter(
              value: _value / 100,
              duration: const Duration(seconds: 1),
              fractionDigits: 2,
              textStyle: TextStyle(
                fontSize: 30,
                fontWeight: FontWeight.bold,
                color: Colors.orange,
              ),
              suffix: "%",
            ),
          ],
        ),
        
        const SizedBox(height: 10),
        Text(
          '(每3秒自动更新)',
          style: TextStyle(fontSize: 14, color: Colors.grey),
        ),
      ],
    );
  }
}